import { PlusOutlined } from '@ant-design/icons'
import {
  Row,
  Typography,
  Flex,
  Button,
  Col,
  Form,
  Input,
  Modal,
  Table,
  Switch,
  Divider,
  Radio,
  Select,
  message
} from 'antd'
import React, { useState, useEffect } from 'react'
import {
  accountAddAPI,
  accountDelAPI,
  accountListAPI, accountQueryAPI,
  accountResetAPI,
  accountUpdateStatusAPI,
  accountUpdateAPI
} from '../service/account'
import { sellerVerifyList } from '../service/seller'

function PrivilegeAccount() {
  const [isModalOpen, setIsModalOpen] = useState(false)
  const [form] = Form.useForm()
  const [accountList, setAccountList] = useState([])
  const [pageNo, setPageNo] = useState(1)
  const [pageSize, setPageSize] = useState(10)
  // 保存商家列表
  const [sellerList, setSellerList] = useState([])
  // 保存账号类型
  const [accountType, setAccountType] = useState(0)
  // 用于更新列表啊
  const [n, setN] = useState(0)
  // 编辑模式标记
  const [isEditMode, setIsEditMode] = useState(false)
  useEffect(() => {
    ;(async () => {
      const res = await accountListAPI({ pageSize, pageNo })
      setAccountList(res.data.objects)
      console.log(res)
    })()
    // 查询所有的商家
    ;(async () => {
      const res = await sellerVerifyList({ pageSize: 1000, pageNo: 1 })
      console.log(res)
      setSellerList(res.data.objects)
    })()
  }, [pageNo, n])
  return (
    <>
      <Row className="info">
        <Col span={24}>
          <Flex justify={'space-between'}>
            <Typography.Title level={3}>权限管理</Typography.Title>
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={() => setIsModalOpen(true)}
            >
              新建账号
            </Button>
          </Flex>
        </Col>
      </Row>
      <Row className="container">
        <Col span={24}>
          <Form layout="inline" onFinish={async (values) => {
            // 实现查询功能，调用后端接口
            try {
              const res = await accountQueryAPI({
                pageSize,
                pageNo: 1, // 重置到第一页
                ...values
              });
              setAccountList(res.data.objects);
              setPageNo(1); // 重置页码
            } catch (error) {
              console.error('查询失败:', error);
              message.error('查询失败，请重试');
            }
          }}>
            <Form.Item label="用户名" name="nickname">
              <Input />
            </Form.Item>
            <Form.Item label="手机号" name="accountPhone">
              <Input />
            </Form.Item>
            <Form.Item label="用户类型" name="accountType">
              <Radio.Group>
                <Radio value={0}>平台</Radio>
                <Radio value={1}>商家</Radio>
              </Radio.Group>
            </Form.Item>
            <Form.Item>
              <Button type="default" htmlType="reset">
                重置
              </Button>
            </Form.Item>
            <Form.Item>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
            </Form.Item>
          </Form>
        </Col>
      </Row>
      <Row className="container">
        <Col span={24}>
          <Typography.Paragraph style={{ fontSize: 16 }}>
            账号列表
          </Typography.Paragraph>
        </Col>
        <Col span={24}>
          <Table
            pagination={{
              pageSize,
              onChange: (page) => {
                setPageNo(page)
              }
            }}
            rowKey={(record) => record.id}
            columns={[
              {
                title: '编号',
                dataIndex: 'id',
                key: 'id'
              },
              {
                title: '姓名',
                dataIndex: 'nickname',
                key: 'nickname'
              },
              {
                title: '商家绑定',
                dataIndex: 'businessId',
                key: 'businessId',
                render: (_, record) => {
                  return record.businessId > 0 ? <>已绑定</> : <>未绑定</>
                }
              },
              {
                title: '用户类型',
                dataIndex: 'accountType',
                key: 'accountType',
                render: (_, record) =>
                  record.accountType === 0 ? <>平台</> : <>商家</>
              },
              {
                title: '手机号',
                dataIndex: 'accountPhone',
                key: 'accountPhone'
              },
              {
                title: '电子邮箱',
                dataIndex: 'email',
                key: 'email'
              },
              {
                title: '角色',
                key: 'role',
                render: (_, record) => '管理员'
              },
              {
                title: '状态',
                key: 'accountStatus',
                render: (_, record) => (
                  <Switch
                    checked={record.accountStatus === 0 ? true : false}
                    onChange={async (checked) => {
                      try {
                        // 调用后端API更新账号状态
                        const status = checked ? 0 : 1;
                        // 这里假设存在一个更新状态的API，如果没有则需要在service/account.js中添加
                        // alert(status);
                        const res = await accountUpdateStatusAPI({
                          id: record.id,
                          accountStatus: status
                        });
                        if (res.code === '0') {
                          message.success('状态更新成功');
                          // 更新本地状态，避免页面刷新
                          const newAccountList = [...accountList];
                          const index = newAccountList.findIndex(item => item.id === record.id);
                          if (index !== -1) {
                            newAccountList[index].accountStatus = status;
                            setAccountList(newAccountList);
                          }
                        } else {
                          message.error('状态更新失败：' + res.msg);
                        }
                      } catch (error) {
                        console.error('更新状态失败:', error);
                        message.error('状态更新失败，请重试');
                      }
                    }}
                  />
                )
              },
              {
                title: '操作',
                key: 'action',
                render: (_, record) => {
                  return (
                    <span className="op">
                      <a
                        onClick={() => {
                          setIsEditMode(true)
                          setIsModalOpen(true)
                          form.setFieldsValue(record)
                        }}
                      >
                        编辑
                      </a>
                      <a
                        onClick={async () => {
                          const res = await accountDelAPI({ id: record.id })
                          console.log(res)
                          if (res.code === '0') {
                            message.success('删除成功')
                            setN(n + 1)
                          }
                        }}
                      >
                        删除
                      </a>
                      <a>分配角色</a>
                      <a
                        onClick={async () => {
                          const res = await accountResetAPI({ id: record.id })
                          console.log(res)
                          if (res.code === '0') {
                            message.success('密码重置成功')
                          }
                        }}
                      >
                        密码重置
                      </a>
                    </span>
                  )
                }
              }
            ]}
            dataSource={accountList}
          />
        </Col>
      </Row>
      <Modal
        title={isEditMode ? "编辑账号" : "新建账号"}
        width={800}
        open={isModalOpen}
        onOk={() => {
          form.submit()
        }}
        onCancel={() => {
          setIsModalOpen(false)
          setIsEditMode(false)
        }}
        maskClosable={false}
        destroyOnClose
      >
        <Divider />
        <Form
          form={form}
          preserve={false}
          onFinish={async (values) => {
            console.log(values)
            try {
              let res;
              if (isEditMode) {
                // 编辑模式下调用更新API，过滤空密码字段
                const updateValues = { ...values };
                if (!updateValues.accountPassword) {
                  delete updateValues.accountPassword;
                }
                console.log('更新参数:', updateValues);
                res = await accountUpdateAPI(updateValues);
                if (res.code === '0') {
                  message.success('账号编辑成功');
                }
              } else {
                // 新增模式下调用新增API
                res = await accountAddAPI(values);
                if (res.code === '0') {
                  message.success('新建账号成功');
                }
              }
              
              if (res.code === '0') {
                setIsModalOpen(false);
                form.resetFields();
                setIsEditMode(false);
                setN(n + 1);
              } else {
                message.error(res.msg || (isEditMode ? '编辑失败' : '新建失败'));
              }
            } catch (error) {
              console.error(isEditMode ? '编辑失败:' : '新建失败:', error);
              message.error(isEditMode ? '编辑失败，请重试' : '新建失败，请重试');
            }
          }}
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 16 }}
        >
          {/* 隐藏的id字段 */}
          <Form.Item name="id" hidden>
            <Input />
          </Form.Item>
          
          <Form.Item label="账号类型" name="accountType" initialValue={0}>
            <Radio.Group
              onChange={(e) => {
                // 清空表单控件输入的值
                form.setFieldsValue({
                  accountPassword: '',
                  accountPhone: '',
                  businessId: '',
                  email: '',
                  nickname: ''
                })
                setAccountType(e.target.value)
              }}
            >
              <Radio value={0}>平台</Radio>
              <Radio value={1}>商家</Radio>
            </Radio.Group>
          </Form.Item>

          {accountType === 0 && (
            <>            
              {/* 平台账号默认商家ID为0 */}
              <Form.Item name="businessId" initialValue={0} hidden>
                <Input />
              </Form.Item>
              <Form.Item
                label="手机号码"
                name="accountPhone"
                rules={[
                  {
                    required: true,
                    message: '电话号码不能为空'
                  },
                  {
                    pattern: /^1[3-9]\d{9}$/,
                    message: '请输入正确的手机号码'
                  }
                ]}
              >
                <Input placeholder="请输入11位手机号" />
              </Form.Item>
              <Form.Item
                label="登录密码"
                name="accountPassword"
                rules={[
                  {
                    required: !isEditMode, // 编辑模式下密码非必填
                    message: '密码不能为空'
                  },
                  {
                    pattern: /^(?=.*[a-zA-Z])(?=.*\d)[a-zA-Z\d]{8,20}$/,
                    message: '请输入8~20个字符且包含字母、数字至少一种'
                  }
                ]}
              >
                <Input.Password placeholder={isEditMode ? "不修改请保持为空" : "请输入8~20个字符且包含字母、数字至少一种"} />
              </Form.Item>
              <Form.Item
                label="用户名称"
                name="nickname"
                rules={[
                  {
                    required: true,
                    message: '用户名称不能为空'
                  },
                  {
                    pattern: /^.{1,15}$/,
                    message: '请输入15个字符以内的用户名'
                  }
                ]}
              >
                <Input placeholder="请输入15个字符以内的用户名" />
              </Form.Item>
              <Form.Item
                label="电子邮箱"
                name="email"
                rules={[
                  {
                    required: true,
                    message: '电子邮箱不能为空'
                  },
                  {
                    pattern:
                      /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/,
                    message: '请输入正确的电子邮箱'
                  }
                ]}
              >
                <Input placeholder="请输入电子邮箱" />
              </Form.Item>
              <Form.Item label="状态" name="accountStatus" initialValue={0}>
                <Radio.Group>
                  <Radio value={0}>启用</Radio>
                  <Radio value={1}>关闭</Radio>
                </Radio.Group>
              </Form.Item>
            </>
          )}
          {accountType === 1 && (
            <>
              <Form.Item
                label="归属商家"
                name="businessId"
                rules={[
                  {
                    required: true,
                    message: '商家名称不能为空'
                  }
                ]}
              >
                <Select
                  placeholder="请选择商家名称"
                  options={sellerList}
                  fieldNames={{ value: 'id', label: 'businessName' }}
                />
              </Form.Item>
              <Form.Item
                label="手机号码"
                name="accountPhone"
                rules={[
                  {
                    required: true,
                    message: '电话号码不能为空'
                  },
                  {
                    pattern: /^1[3-9]\d{9}$/,
                    message: '请输入正确的手机号码'
                  }
                ]}
              >
                <Input placeholder="请输入11位手机号" />
              </Form.Item>
              <Form.Item
                label="登录密码"
                name="accountPassword"
                rules={[
                  {
                    required: !isEditMode, // 编辑模式下密码非必填
                    message: '密码不能为空'
                  },
                  {
                    pattern: /^(?=.*[a-zA-Z])(?=.*\d)[a-zA-Z\d]{8,20}$/,
                    message: '请输入8~20个字符且包含字母、数字至少一种'
                  }
                ]}
              >
                <Input.Password placeholder={isEditMode ? "不修改请保持为空" : "请输入8~20个字符且包含字母、数字至少一种"} />
              </Form.Item>
              <Form.Item
                label="用户名称"
                name="nickname"
                rules={[
                  {
                    required: true,
                    message: '用户名称不能为空'
                  },
                  {
                    pattern: /^.{1,15}$/,
                    message: '请输入15个字符以内的用户名'
                  }
                ]}
              >
                <Input placeholder="请输入15个字符以内的用户名" />
              </Form.Item>
              <Form.Item
                label="电子邮箱"
                name="email"
                rules={[
                  {
                    required: true,
                    message: '电子邮箱不能为空'
                  },
                  {
                    pattern:
                      /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/,
                    message: '请输入正确的电子邮箱'
                  }
                ]}
              >
                <Input placeholder="请输入电子邮箱" />
              </Form.Item>
              <Form.Item label="状态" name="accountStatus" initialValue={0}>
                <Radio.Group>
                  <Radio value={0}>启用</Radio>
                  <Radio value={1}>关闭</Radio>
                </Radio.Group>
              </Form.Item>
            </>
          )}
        </Form>
      </Modal>
    </>
  )
}

export default PrivilegeAccount
